package com.example.concurrency.chapter10;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class SemaphoreTests {
    private static Semaphore semaphore = new Semaphore(2);

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++){
            new Thread(new Task()).start();
        }
    }

    static class Task implements Runnable {

        @Override
        public void run() {
            try {
                String name = Thread.currentThread().getName();
                semaphore.acquire();
                System.out.println("线程【" + name +"】" + "得到资源");
                Thread.sleep(new Random().nextInt(3) * 1000 + 2000);
                System.out.println("线程【" + name +"】" + "释放资源");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release();
            }
        }
    }
}
